package org.shoukaiseki.tencent.live.service.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.*;
import org.shoukaiseki.common.logger.Logger;
import org.shoukaiseki.tencent.live.config.TencentLiveCoreProperties;
import org.shoukaiseki.tencent.live.logger.TencentLiveLoggers;
import org.shoukaiseki.tencent.live.service.TencentLiveManagerService;
import org.shoukaiseki.tencent.live.utils.TencentLiveUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.NumberUtils;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@Service
public class TencentLiveManagerServiceImpl implements TencentLiveManagerService {

    public static final Logger logger = TencentLiveLoggers.DEFAULT_LOGGER;

    @Resource
    TencentLiveCoreProperties tencentLiveCoreProperties;


    @Resource(name = "liveCredential")
    Credential credential;

    @Resource
    LiveClient liveClient;

    @Override
    public StreamOnlineInfo[] describeLiveStreamOnlineList(String streamName, Number pageNum,Number pageSize){
        DescribeLiveStreamOnlineListRequest request = new DescribeLiveStreamOnlineListRequest();
        request.setPageNum(NumberUtils.convertNumberToTargetClass(pageNum,Long.class));
        request.setPageSize(NumberUtils.convertNumberToTargetClass(pageSize,Long.class));
        request.setDomainName(this.tencentLiveCoreProperties.getLivePushDomainName());
        request.setAppName(tencentLiveCoreProperties.getAppName());
        request.setStreamName(streamName);
        DescribeLiveStreamOnlineListResponse response = null;
        try {
            response = liveClient.DescribeLiveStreamOnlineList(request);
        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云接口获取错误",e);
            throw new RuntimeException("腾讯云接口获取错误",e);
        }
        return response.getOnlineInfo();
    }

    @Override
    public Integer describeLiveStreamState(String streamName) {
        DescribeLiveStreamStateRequest request = new DescribeLiveStreamStateRequest();
        request.setDomainName(this.tencentLiveCoreProperties.getLivePushDomainName());
        request.setAppName(tencentLiveCoreProperties.getAppName());
        request.setStreamName(streamName);
        try {
            DescribeLiveStreamStateResponse response = liveClient.DescribeLiveStreamState(request);
                return TencentLiveUtils.streamStateToInteger(response.getStreamState());
        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云接口获取错误",e);
            throw new RuntimeException("腾讯云接口获取错误",e);
        }
    }


    @Override
    public boolean forbidLiveStream(Number forbidMinute,String streamName) {
        ForbidLiveStreamRequest request = new ForbidLiveStreamRequest();
        request.setStreamName(streamName);
        request.setAppName(tencentLiveCoreProperties.getAppName());
        request.setDomainName(tencentLiveCoreProperties.getLivePushDomainName());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = new Date();
//        LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
        date.setTime(date.getTime()+(1000*60));
        String format = sdf.format(date);
        logger.infoLambar(()->{
            logger.info(format);
            logger.info("{}禁用至{}",streamName,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
        });
        request.setResumeTime(format);
        try {
            ForbidLiveStreamResponse response = liveClient.ForbidLiveStream(request);
            logger.infoLambar(()->{
               logger.info("response.id="+response.getRequestId());
            });

        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云接口调用错误",e);
            return false;
        }
        return true;
    }

    @Override
    public boolean resumeLiveStream(String streamName) {
        ResumeLiveStreamRequest request = new ResumeLiveStreamRequest();
        request.setStreamName(streamName);
        request.setAppName(tencentLiveCoreProperties.getAppName());
        request.setDomainName(tencentLiveCoreProperties.getLivePushDomainName());
        try {
            ResumeLiveStreamResponse response = liveClient.ResumeLiveStream(request);
            logger.infoLambar(()->{
                logger.info("response.id="+response.getRequestId());
            });
        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云接口调用错误",e);
            return false;
        }
        return true;
    }

    @Override
    public String generatorRtmpPushUrl(Number effectivetime, String streamName){
        if(effectivetime==null){
            //默认5分钟
            effectivetime=5;
        }
        long txTime = new Date().getTime()/1000;
        txTime+=NumberUtils.convertNumberToTargetClass(effectivetime,Long.class)*60L;
        String safeUrl = TencentLiveUtils.getSafeUrl(tencentLiveCoreProperties.getLiveDomainKey(), streamName, txTime);
        return new StringBuilder("rtmp://").append(tencentLiveCoreProperties.getLivePushDomainName()).append("/").append(tencentLiveCoreProperties.getAppName())
        .append("/").append(streamName).append("?").append(safeUrl).toString();
    }

    @Override
    public String generatorRtmpPullUrl(String streamName){
        return new StringBuilder("http://").append(tencentLiveCoreProperties.getLivePullDomainName()).append("/").append(tencentLiveCoreProperties.getAppName())
                .append("/").append(streamName).append(".m3u8").toString();
    }

    @Override
    public boolean dropLiveStream(@NotEmpty String streamName) {
        DropLiveStreamRequest req = new DropLiveStreamRequest();
        try {
            liveClient.DropLiveStream(req);
        } catch (TencentCloudSDKException e) {
            logger.error("腾讯云接口调用错误",e);
            return false;
        }
        return true;
    }
}
